package com.bqy.myokgo.base.okgo.callback;

import android.app.Activity;

import com.bqy.myokgo.base.manager.HttpManager;
import com.bqy.myokgo.base.okgo.bean.GuestBean;
import com.bqy.myokgo.base.okgo.bean.XXResponse;
import com.lzy.okgo.request.base.Request;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Response;

public abstract class HttpManagerCallback<T> extends Callback<T> {
    private Type type;
    private Class<T> clazz;
    private String TAG;
    private Activity context;

    public HttpManagerCallback(Activity activity, String TAG) {
        super();
        this.context = activity;
        this.TAG = TAG;
        HttpManager.getInstance().addListener(context);
    }

    /**
     * 网络请求开始
     */
    @Override
    public void onStart(Request<T, ? extends Request> request) {
        super.onStart(request);
        request.tag(TAG);
        HttpManager.getInstance().addHttpFlag(TAG);
    }

    /**
     * 失败
     */
    @Override
    public void onError(com.lzy.okgo.model.Response<T> response) {
        super.onError(response);
        com.lzy.okgo.model.Response<XXResponse<GuestBean>> responses = (com.lzy.okgo.model.Response<XXResponse<GuestBean>>) response;
        HttpManager.getInstance().cancelAll(responses);
    }

    /**
     * 该方法是子线程处理，不能做ui相关的工作
     * 主要作用是解析网络返回的 response 对象,生产onSuccess回调中需要的数据对象
     * 这里的解析工作不同的业务逻辑基本都不一样,所以需要自己实现,以下给出的时模板代码,实际使用根据需要修改
     */
    @Override
    public T convertResponse(Response response) throws Throwable {
        if (type == null) {
            if (clazz == null) {
                Type genType = getClass().getGenericSuperclass();
                type = ((ParameterizedType) genType).getActualTypeArguments()[0];
            } else {
                JsonConvert<T> convert = new JsonConvert<>(clazz);
                return convert.convertResponse(response);
            }
        }
        JsonConvert<T> convert = new JsonConvert<>(type);

        HttpManager.getInstance().addHttpOK(TAG, convert.convertResponse(response));
        return convert.convertResponse(response);
    }


}